/* 
 * CS:APP Data Lab 
 * 
 * <Please put your name and userid here>
 * 
 * bits.c - Source file with your solutions to the Lab.
 *          This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the <stdio.h> header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * <stdio.h>, although you might get a compiler warning. In general,
 * it's not good practice to ignore compiler warnings, but in this
 * case it's OK.  
 */

#if 0
/*
 * Instructions to Students:
 *
 * STEP 1: Read the following instructions carefully.
 */

You will provide your solution to the Data Lab by
editing the collection of functions in this source file.

INTEGER CODING RULES:
 
  Replace the "return" statement in each function with one
  or more lines of C code that implements the function. Your code 
  must conform to the following style:
 
  int Funct(arg1, arg2, ...) {
      /* brief description of how your implementation works */
      int var1 = Expr1;
      ...
      int varM = ExprM;

      varJ = ExprJ;
      ...
      varN = ExprN;
      return ExprR;
  }

  Each "Expr" is an expression using ONLY the following:
  1. Integer constants 0 through 255 (0xFF), inclusive. You are
      not allowed to use big constants such as 0xffffffff.
  2. Function arguments and local variables (no global variables).
  3. Unary integer operations ! ~
  4. Binary integer operations & ^ | + << >>
    
  Some of the problems restrict the set of allowed operators even further.
  Each "Expr" may consist of multiple operators. You are not restricted to
  one operator per line.

  You are expressly forbidden to:
  1. Use any control constructs such as if, do, while, for, switch, etc.
  2. Define or use any macros.
  3. Define any additional functions in this file.
  4. Call any functions.
  5. Use any other operations, such as &&, ||, -, or ?:
  6. Use any form of casting.
  7. Use any data type other than int.  This implies that you
     cannot use arrays, structs, or unions.

 
  You may assume that your machine:
  1. Uses 2s complement, 32-bit representations of integers.
  2. Performs right shifts arithmetically.
  3. Has unpredictable behavior when shifting if the shift amount
     is less than 0 or greater than 31.


EXAMPLES OF ACCEPTABLE CODING STYLE:
  /*
   * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
   */
  int pow2plus1(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     return (1 << x) + 1;
  }

  /*
   * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
   */
  int pow2plus4(int x) {
     /* exploit ability of shifts to compute powers of 2 */
     int result = (1 << x);
     result += 4;
     return result;
  }

FLOATING POINT CODING RULES

For the problems that require you to implement floating-point operations,
the coding rules are less strict.  You are allowed to use looping and
conditional control.  You are allowed to use both ints and unsigneds.
You can use arbitrary integer and unsigned constants. You can use any arithmetic,
logical, or comparison operations on int or unsigned data.

You are expressly forbidden to:
  1. Define or use any macros.
  2. Define any additional functions in this file.
  3. Call any functions.
  4. Use any form of casting.
  5. Use any data type other than int or unsigned.  This means that you
     cannot use arrays, structs, or unions.
  6. Use any floating point data types, operations, or constants.


NOTES:
  1. Use the dlc (data lab checker) compiler (described in the handout) to 
     check the legality of your solutions.
  2. Each function has a maximum number of operations (integer, logical,
     or comparison) that you are allowed to use for your implementation
     of the function.  The max operator count is checked by dlc.
     Note that assignment ('=') is not counted; you may use as many of
     these as you want without penalty.
  3. Use the btest test harness to check your functions for correctness.
  4. Use the BDD checker to formally verify your functions
  5. The maximum number of ops for each function is given in the
     header comment for each function. If there are any inconsistencies 
     between the maximum ops in the writeup and in this file, consider
     this file the authoritative source.

/*
 * STEP 2: Modify the following functions according the coding rules.
 * 
 *   IMPORTANT. TO AVOID GRADING SURPRISES:
 *   1. Use the dlc compiler to check that your solutions conform
 *      to the coding rules.
 *   2. Use the BDD checker to formally verify that your solutions produce 
 *      the correct answers.
 */


#endif
/* Copyright (C) 1991-2018 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */
/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include <features.h> or any other header that includes
   <features.h> because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */
/* glibc's intent is to support the IEC 559 math functionality, real
   and complex.  If the GCC (4.9 and later) predefined macros
   specifying compiler intent are available, use them to determine
   whether the overall intent is to support these features; otherwise,
   presume an older compiler has intent to support these features and
   define these macros by default.  */
/* wchar_t uses Unicode 10.0.0.  Version 10.0 of the Unicode Standard is
   synchronized with ISO/IEC 10646:2017, fifth edition, plus
   the following additions from Amendment 1 to the fifth edition:
   - 56 emoji characters
   - 285 hentaigana
   - 3 additional Zanabazar Square characters */
/* We do not support C11 <threads.h>.  */
/* 
 * bitOr - x|y using only ~ and & 
 *   Example: bitOr(6, 5) = 7
 *   Legal ops: ~ &
 *   Max ops: 8
 *   Rating: 1
 */
int bitOr(int x, int y) {
  // De Morgan's law
  return ~(~x & ~y);
}
/* 
 * tmin - return minimum two's complement integer 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 4
 *   Rating: 1
 */
int tmin(void) {
  return 1 << 31;
}
/* 
 * negate - return -x 
 *   Example: negate(1) = -1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int negate(int x) {
  return ~x + 1;
}
/* 
 * getByte - Extract byte n from word x
 *   Bytes numbered from 0 (least significant) to 3 (most significant)
 *   Examples: getByte(0x12345678,1) = 0x56
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 6
 *   Rating: 2
 */
int getByte(int x, int n) {
  int shift = n << 3;
  int mask = 0xff << shift;
  // If (x & mask) is a negative number, then the higher 24 bits of (x & 
  // mask) >> shift are 0x1.
  // Therefore, the final result is ((x & mask) >> shift) & 0xff.   
  return ((x & mask) >> shift) & 0xff;
}
/* 
 * dividePower2 - Compute x/(2^n), for 0 <= n <= 30
 *  Round toward zero
 *   Examples: dividePower2(15,1) = 7, dividePower2(-33,4) = -2
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int dividePower2(int x, int n) { 
  // If x is zero or positive number, then return x >> n directly.
  // If x is a negative number, we should assign x with the plus of x and
  // (2^n - 1) and then return x >> n;
  // Therefore, we need a control expression to control whether we should
  // assign x with the plus of x and (2^n - 1) according to the sign of x.
  // Here I construct x >> 31 to serve as above control expression.
  // If x is zero or positive number, then control would be 0 and add would 
  // be 0 which would have no influence on the value of x.
  // If x is a negative number, then control would be ~0 and add would be
  // (2^n - 1)

  int control = x >> 31;
  int add = control & ((1 << n) + ~0);
  x = x + add;
  return x >> n; 
}
/* 
 * logicalShift - shift x to the right by n, using a logical shift
 *   Can assume that 0 <= n <= 31
 *   Examples: logicalShift(0x87654321,4) = 0x08765432
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 3 
 */
int logicalShift(int x, int n) {
  // In order to explain the solution easily, let us represent a integer x
  // with such pattern [x31:x0] among which the number near x represent the 
  // number th bit of x.
  // If x is zero or positive number, then x >> n would be like 0...0
  // [x31:xn].
  // If x is a negative number, then x >> n would be like 1...1[x31:xn].
  // Therefore, what we should do is to reset the higher n bits of 
  // (x >> n).
  // We would follow three steps to construct the mask to accomplish that.
  // The first step is to compute (1 << n) - 1 whose bit representation
  // would be like 1...1. <1>
  // The second step is to compute <1> << (32 - n) whose bit representation
  // would be like 1...10...0. <2> 
  // The third step is to compute ~<2> whose bit representation would be
  // like 0...01...1. <3>

  int var1 = (1 << n) + ~0;
  int neg_n = ~n + 1;
  int var2 = var1 << (32 + neg_n);
  int var3 = ~var2;
  return (x >> n) & var3;
}
/* 
 * isPositive - return 1 if x > 0, return 0 otherwise 
 *   Example: isPositive(-1) = 0.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 8
 *   Rating: 2
 */
int isPositive(int x) {
  int symbol = (x >> 31) & 1;
  int bool_x = !(!x);
  return (!symbol) & bool_x;
}
/* 
 * isLess - if x < y  then return 1, else return 0 
 *   Example: isLess(4,5) = 1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 24
 *   Rating: 3
 */
int isLess(int x, int y) {
  // I am so lazy that I decide to apply the former solution.
  // However, the former solution is to judge whether x is less or equal 
  // than y, but we could change that solution slightly to acquire another
  // solution which could judge whether x is larger or equal than y.
  // And then we just negete the result about whether x is larger or equal 
  // than to acquire the answer of the present question.

  int x_symbol = (x >> 31) & 1;
  int y_symbol = (y >> 31) & 1;
  int control = x_symbol ^ y_symbol;
  int neg_y = ~y + 1;
  int minus = (x + neg_y);
  int minus_symbol = (minus >> 31) & 1;
  int equal_flag = !(x ^ y);
  int large_or_equal = equal_flag | (
                       (control & y_symbol) | 
                       (!(minus_symbol | control)));
  return !large_or_equal;
}
/* 
 * bang - Compute !x without using !
 *   Examples: bang(3) = 0, bang(0) = 1
 *   Legal ops: ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 4 
 */
int bang(int x) {
  int neg_x = ~x + 1;
  int tmin = 1 << 31;
  int symbol = (x ^ neg_x) >> 31; // if x is zero, then symbol is 0x0
                                  // while symbol is 0xffffffff
  int control = (x ^ tmin) >> 31; // used to select 0, reject 0x80000000
  return (symbol + 1) & control;
}
/*
 * isPower2 - returns 1 if x is a power of 2, and 0 otherwise
 *   Examples: isPower2(5) = 0, isPower2(8) = 1, isPower2(0) = 0
 *   Note that no negative number is a power of 2.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 4
 */
int isPower2(int x) {
  // Dennis Ritchie's kill the rightmost 1 algorithm!
  
  int symbol_x = (x >> 31) & 1;
  int bool_x = !(!x);
  int temp = x & (x + ~0);
  return ((!symbol_x) & bool_x) // reject negative number and zero
         & !temp;
}
/* howManyBits - return the minimum number of bits required to represent x in
 *             two's complement
 *  Examples: howManyBits(12) = 5
 *            howManyBits(298) = 10
 *            howManyBits(-5) = 4
 *            howManyBits(0)  = 1
 *            howManyBits(-1) = 1
 *            howManyBits(0x80000000) = 32
 *  Legal ops: ! ~ & ^ | + << >>
 *  Max ops: 90
 *  Rating: 4
 */
int howManyBits(int x) {
  int target = x >> 31;     // the destination of sars
  int low = 0;         
  int high = 31;
  int mid;                  // used for binary-search
  int temp;                 // record the result of sars
  int control;              // used for condition
  int not_temp_xor_target;  // the factor of control
  
  // The loop body would consume 15 ops.
  // After repeating five times, it would just consume 75 ops.
 
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
 
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);

  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);

  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
  
  mid = (low + high) >> 1;
  temp = x >> mid;
  not_temp_xor_target = !(temp ^ target);
  control = ~not_temp_xor_target + 1;
  high ^= (high ^ mid) & control;
  low ^= (low ^ (mid + 1)) & (~control);
  
  // Thanks to binary-search, even repeatedly exceuting unnecessary  
  // code, it would always get the right answer.

  return low + 1;
}
/* 
 * floatNegate - Return bit-level equivalent of expression -f for
 *   floating point argument f.
 *   Both the argument and result are passed as unsigned int's, but
 *   they are to be interpreted as the bit-level representations of
 *   single-precision floating point values.
 *   When argument is NaN, return argument.
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 10
 *   Rating: 2
 */
unsigned floatNegate(unsigned uf) {
   
  int exponent_mask = 0x7f800000; // select the exponent part of float
  int fraction_mask = 0x7fffff;
  int unshift_exponent = (uf & exponent_mask); 
  int fraction = (uf & fraction_mask);
  
  if(unshift_exponent == exponent_mask && fraction)
    return uf;
  else
    return uf ^ 0x80000000;
}
/* 
 * floatInt2Float - Return bit-level equivalent of expression (float) x
 *   Result is returned as unsigned int, but
 *   it is to be interpreted as the bit-level representation of a
 *   single-precision floating point values.
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
 *   Max ops: 30
 *   Rating: 4
 */
unsigned floatInt2Float(int x) {

  int symbol_x = (x >> 31) & 1;
  int lm_one_loc = 31; // record the location about the lefmost one in 'x'
  int temp1, temp2, temp3;
  int fraction;
  int exponent;
  int standard;

  if(x == 0x80000000)
    return 0xcf000000;
  if(!x)
    return 0;

  if(symbol_x)
    x = -x;

  temp1 = x;

  while(temp1 >= 0) {
    temp1 <<= 1;
    --lm_one_loc;
  }
  
  fraction = x ^ (1 << lm_one_loc) ;
  if(lm_one_loc <= 23) 
    fraction <<= (23 - lm_one_loc);
  else {
    // Roundings to nearest, ties to even
    temp3 = lm_one_loc - 23; // indicate how many bits deleted are.
    temp2 = 1 << temp3; // prepare to construct mask to extract bits deleted
    temp1 = fraction & (temp2 - 1); // bits deleted
    standard = temp2 >> 1; // standard which would be used to round
    fraction >>= temp3; // round down
    if(temp1 > standard)
      ++fraction; // round up
    if(temp1 == standard && fraction % 2)
      ++fraction; // round up to even
  }
  exponent = lm_one_loc + 127;
  return (symbol_x << 31) + (
         (exponent << 23) +
         fraction); 
}
